﻿using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Caseify.Utility;

namespace Caseify.Commands
{
    [Command(PackageIds.TitleCase)]
    internal sealed class TitleCase : BaseCommand<TitleCase>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            //await Transform.TextConverterAsync(CultureInfo.CurrentCulture.TextInfo.ToTitleCase);
            await Transform.TextConverterAsync(ConvertToTitleCase2);
        }

        private static string ConvertToTitleCase(string selectedText)
        {
            var charInSelectedText = Transform.TextToChars(selectedText);
            var firstChar = charInSelectedText[0];
            var listOfCharInSelectedText = charInSelectedText.ToList();
            listOfCharInSelectedText.Remove(firstChar);
            var text = firstChar.ToString().ToUpper() + string.Join("", listOfCharInSelectedText.ToArray());
            return text;
        }

        private static string ConvertToTitleCase2(string selectedText)
        {
            var charInSelectedText = Transform.TextToChars(selectedText);
            var firstChar = charInSelectedText[0];
            var listOfCharInSelectedText = charInSelectedText.ToList();
            listOfCharInSelectedText.Remove(firstChar);

            var length = listOfCharInSelectedText.Count;
            var emptyStrIndex = new List<int>();

            for (int i = 0; i < length; i++)
            {
                var item = listOfCharInSelectedText[i];
                if (item == ' ' || item == '_')
                {
                    emptyStrIndex.Add(i);

                    if (i + 1 < length)
                    { 
                        var item2 = listOfCharInSelectedText[i + 1];
                        listOfCharInSelectedText[i + 1] = item2.ToString().ToUpper().ToCharArray()[0];
                    }
                }
            }

            var removeIdx = 0;
            foreach (var index in emptyStrIndex)
            {
                listOfCharInSelectedText.RemoveAt(index - removeIdx);
                removeIdx += 1;
            }

            var text = firstChar.ToString().ToUpper() + string.Join("", listOfCharInSelectedText.ToArray());
            return text;
        }
    }
}
